<template>
  <!-- （Products.vue文件）此页方法是用vuex全局数据来获取加载数据的 -->
  <!-- <ul>
    <li v-for="item in $store.state.list" :key="item._id">
      {{ item.name }} ￥{{ item.price }}——
      <button @click="buyHandle(item._id)">购买</button>
    </li>
    <keep-alive>
      <button v-show="isShowLoadMore" @click="loaData">加载数据</button>
    </keep-alive>
  </ul> -->
  <!-- 卡片 -->
  <div>
    <van-card
      v-for="item in $store.state.list"
      :key="item._id"
      :num="item.quantity"
      :price="item.price"
      :title="item.name"
      :thumb="item.coverImg | resetImg"
    >
      <template #footer>
        <van-button type="danger" size="mini" @click="buyHandle(item._id)"
          >添加</van-button
        >
        <van-button type="danger" size="mini">购买</van-button>
      </template>
    </van-card>
    <keep-alive>
      <button v-show="isShowLoadMore" @click="loaData">加载数据</button>
    </keep-alive>
  </div>
</template>

<script>
import { getList } from '../services/products'
import { addToCart } from '../services/shopcarts'
// import { mapMutations } from 'vuex'
// import { serverUrl } from '../utils/config'

export default {
  data() {
    return {
      // list: [],
      isShowLoadMore: true
    }
  },
  async created() {
    const res = await getList()
    this.list = res.products
  },
  // 局部过滤器 处理图片路径问题
  /*  filters: {
    resetImg(str) {
      if (str && str.startsWith('http')) {
        return str
      } else {
        return serverUrl + str
      }
    }
  }, */
  methods: {
    async buyHandle(id) {
      const res = await addToCart(id)
      alert('添加成功')
      console.log(res)
    },
    loaData() {
      if (this.$store.state.pages < this.$store.state.page) {
        this.isShowLoadMore = false
        return
      }
      this.$store.dispatch('loadData', { page: this.$store.state.page })
    }
  }
}
</script>

<style scoped>
ul {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  width: 100%;
}
ul li {
  flex: 1;
  flex-direction: row;
  height: 50px;
  display: flex;
  padding: 0.1rem 0.2rem;
}
/* button {
  width: 100px;
} */
</style>
